package com.jdcjk.util;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import static org.greenrobot.eventbus.EventBus.TAG;


/**
 * Created by dong on 2016/8/9.
 * Home键监听广播
 */
public class OnKeyDownReceiver extends BroadcastReceiver {
    // 上下文对象
    private static Activity context;
    // 广播接受者
    private static OnKeyDownReceiver receiver;
    // 静态变量
    private static final String SYSTEM_REASON = "reason";
    private static final String SYSTEM_HOME_KEY = "homekey";
    private static final String SYSTEM_HOME_KEY_LONG = "recentapps";

    private OnKeyDownReceiver(Activity context) {
        super();
        OnKeyDownReceiver.context = context;
    }

    public static OnKeyDownReceiver getOnHomeDownReceiver(Activity context) {
        if (receiver == null) {
            synchronized (OnKeyDownReceiver.class) { // 同步锁
                if (receiver == null) {
                    receiver = new OnKeyDownReceiver(context);
                }
            }
        }
        return receiver;
    }

    /**
     * 注册Home键监听广播
     */
    public static void registerOnHomeDownReceiver() {
        IntentFilter homeFilter = new IntentFilter();
        homeFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        homeFilter.addAction(Intent.ACTION_SCREEN_OFF);
        context.registerReceiver(receiver, homeFilter);
    }

    /**
     * 注销Home键监听广播
     */
    public static void unRegisterOnHomeDownReceiver() {
        if (receiver != null) {
            try {
                context.unregisterReceiver(receiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        receiver = OnKeyDownReceiver.this;
        String action = intent.getAction();
        L.i(TAG, "onReceive:action " + action);
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_REASON);
            L.i(TAG, "onReceive:reason " + reason);
            if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                // 表示按了home键,程序到了后台
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                context.startActivity(intent);
            } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                // 表示长按home键,显示最近使用的程序列表
                // 表示按了home键,程序到了后台
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                context.startActivity(intent);
            }
        } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
            // 表示长按power键,关闭了屏幕
        }
    }
}
